#!/usr/bin/env python
#
# Copyright (C) 2007 Jason Kivlighn
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, #USA.

from pychart import *
import time
import sys, os
import timeline_data as tl
import mtzcolor

def ts_to_str(ts):
  return time.strftime("%b %d, %Y",time.gmtime(times[ts/2]))

if len(sys.argv) < 2:
  print "Usage ./pychart_wave.py <user>"
  sys.exit(1)
  
user = sys.argv[1]

### Options ###
TICKS = 10
SIZE = (1500,700)
#LEGEND = legend.T()
LEGEND = None
theme.scale_factor = 3
theme.output_format = "png"
theme.output_file = "lastfm-%s.%s" % (user,theme.output_format)
theme.use_color = True
theme.default_font_size = 9
################
theme.reinitialize()

can = canvas.default_canvas()

times, artist_stack, curved_data = tl.linregress_data("artists",user,threshold=20,interval=1,regression_factor=2)

begin_color = (0.55,1.0,1.0)
end_color = (0.35,1.0,1.0)
color_stack = mtzcolor.colorize_hsv_trans(artist_stack,begin_color,end_color)

#Set up the graph
ar = area.T(x_axis = axis.X(label="Date",
            format=ts_to_str,
            tic_interval=len(curved_data)/TICKS),
            size=SIZE,
            y_axis = axis.Y(label="Play count"),
            x_range = (0,len(curved_data)),
            y_range = (0,None),
            legend=LEGEND
            )

#Plot the graph
i = 0
for artist in artist_stack:
  escaped_artist = font.quotemeta(artist)
  try:
    str(escaped_artist)
  except:
    escaped_artist="?"
  r,g,b = color_stack[artist]
  if i == 0:
    ar.add_plot(range_plot.T(label=escaped_artist,data=curved_data, 
     line_style=None, fill_style = fill_style.Plain(bgcolor=color.T(r=r,g=g,b=b))))
  else:
    ar.add_plot(range_plot.T(min_col=i,max_col=i+1,label=escaped_artist,data=curved_data, 
     line_style=None, fill_style = fill_style.Plain(bgcolor=color.T(r=r,g=g,b=b))))

  i += 1
  
ar.draw(can)

label_positions = tl.label_positions_where_popular(curved_data,artist_stack,3,20)
for artist, (x,y,size) in label_positions.iteritems():
  escaped_artist = "/%.2d{}%s" % (size,font.quotemeta(artist))
  try:
    str(escaped_artist)
  except:
    escaped_artist="?"
  width = font.text_width(escaped_artist)
  x = ar.x_pos(max(1,x-width/2.0))
  y = ar.y_pos(y)
  can.show(x,y,escaped_artist)

print "Created:", theme.output_file
